package service

import (
	"MyBlogv2/common/HttpCode"
	"MyBlogv2/common/define"
	helper2 "MyBlogv2/common/helper"
	"MyBlogv2/common/models"
	"MyBlogv2/common/oss"
	"MyBlogv2/common/response"
	"github.com/gin-gonic/gin"
	"path"
	"strconv"
)

func GetBanners(c *gin.Context) {
	var paths []string
	models.Db.Model(new(models.Banners)).Select("path").Find(&paths)
	c.JSON(200, gin.H{
		"code": 200,
		"data": paths,
		"msg":  "success",
	})
}

func GetBanners4Admin(c *gin.Context) {
	var bannersList []models.Banners
	models.Db.Model(new(models.Banners)).Find(&bannersList)
	response.ResponseOK(c, bannersList)
}

func DelBannerById(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	models.Db.Model(new(models.Banners)).Where("id = ?", id).Delete(new(models.Banners))
	response.ResponseOK(c, nil)
}

func UploadBanner(c *gin.Context) {
	var count int64
	models.Db.Model(new(models.Banners)).Count(&count)
	if int(count) >= define.BANNER_MAX_COUNT {
		response.ResponseError(c, HttpCode.FAILURE)
		return
	}
	file, _ := c.FormFile("bannerImage")
	userId, _ := c.Get("userId")
	filename := file.Filename
	ext := path.Ext(filename)
	objectName := helper2.GetUUID() + ext
	filePath, err := file.Open()
	if err != nil {
		response.ResponseError(c, HttpCode.FILE_UPLOAD_ERROR)
		return
	}
	uploadFilePath, err := oss.UploadFile(objectName, filePath)
	if err != nil {
		response.ResponseError(c, HttpCode.FILE_UPLOAD_ERROR)
		return
	}

	var banners models.Banners
	banners.UserId = userId.(int)
	banners.Path = uploadFilePath
	banners.Size = int(file.Size)
	banners.SortOrder = int(count + 1)
	banners.Type = strconv.Itoa(1)
	models.Db.Model(new(models.Banners)).Create(&banners)
	response.ResponseOK(c, nil)
}
func UpdateSortOrder(c *gin.Context) {
	var bannersList []models.Banners
	if err := c.ShouldBindJSON(&bannersList); err != nil {
		response.ResponseError(c, HttpCode.PARAM_ERROR)
		return
	}
	sql := "delete from t_banners"
	models.Db.Exec(sql)
	for i, banners := range bannersList {
		banners.Id = 0
		banners.SortOrder = i + 1
		models.Db.Model(new(models.Banners)).Create(&banners)
	}
	response.ResponseOK(c, nil)
}
